package com.cash.lemoloan.statisticlib.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;

import com.cash.lemoloan.statisticlib.StatisticApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class BitmapUtil {


    /**
     * 根据图片路径，拿到压缩后的图片base64数据
     * @param imgFile
     * @return
     */
    public static String getImgDataBase64(File imgFile){
        try {
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFile.getAbsolutePath(), newOpts);
            newOpts.inJustDecodeBounds = false;

            int w = newOpts.outWidth;
            int be = w/800;

            newOpts.inSampleSize = be;// 设置缩放比例
            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), newOpts);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            bitmap.recycle();
            byte[] bytes = bos.toByteArray();
            return Base64.encode(bytes);
        }catch(Exception e){
            e.getMessage();
        }
        return "";
    }
    public static String getImgDataBase64(Uri uri){
        try {
//            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(StatisticApplication.getInstance().getContentResolver(), uri);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            bitmap.recycle();
            byte[] bytes = bos.toByteArray();
            return Base64.encode(bytes);
        }catch(Exception e){
            e.getMessage();
        }
        return "";
    }
}
